package com.example.aigc_education.security.config;

import com.example.aigc_education.security.filter.JwtAuthenticationTokenFilter;
import com.example.aigc_education.security.handle.AccessDeniedHandlerImpl;
import com.example.aigc_education.security.handle.AuthenticationEntryPointImpl;
import com.example.aigc_education.security.handle.LogoutSuccessHandlerImpl;
import com.example.aigc_education.security.service.UserDetailsServiceImpl;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.annotation.Resource;

/**
 * 安全配置类
 */
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Resource
    private UserDetailsServiceImpl userDetailsService;

    @Resource
    JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter;

    @Resource
    private MobileAuthenticationConfig mobileAuthenticationConfig;

    @Resource
    private WeChatAuthenticationConfig weChatAuthenticationConfig;

    @Resource
    private AccessDeniedHandlerImpl accessDeniedHandler;

    @Resource
    private AuthenticationEntryPointImpl authenticationEntryPoint;

    @Resource
    private LogoutSuccessHandlerImpl logoutSuccessHandler;



    /**
     * 密码加密
     * @return 密码加密对象
     */
    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }

    /**
     * 配置安全拦截机制
     * @param http http安全对象
     * @throws Exception 异常
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                //关闭csrf
                .csrf().disable()
                //不通过Session获取SecurityContext
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authorizeRequests()
                // 对于登录接口 允许匿名访问
                .antMatchers("/user/loginByUsername", "/wechat/login","/user/loginByMobile ", "/wechat/register", "/captchaImage", "/sms/**", "/llmApp/connect/**").anonymous()
                .antMatchers("/ws/**").authenticated()
                // 除上面外的所有请求全部需要鉴权认证
                .anyRequest().authenticated();

        // 添加自定义过滤器
        http.addFilterBefore(jwtAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);
        //退出登录处理器
        http.logout().logoutUrl("/logout").logoutSuccessHandler(logoutSuccessHandler);

        // 异常处理
        http.exceptionHandling()
                        .authenticationEntryPoint(authenticationEntryPoint)
                        .accessDeniedHandler(accessDeniedHandler);

        // 手机号登录配置
        http.apply(mobileAuthenticationConfig);
        //配置微信登录设置
        http.apply(weChatAuthenticationConfig);
        // 允许跨域
        http.cors();
    }


    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    /**
     * 配置用户信息加载校验
     * @param auth 认证管理构建器
     * @throws Exception 异常
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
    }
}
